package org.gdkm.service.impl;

import mapper.MyMapper;
import org.apache.commons.lang.StringUtils;
import org.gdkm.domin.TbUser;
import org.gdkm.json.MapperUtils;
import org.gdkm.mapper.TbUserMapper;
import org.gdkm.service.LoginService;
import org.gdkm.service.consumer.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import tk.mybatis.mapper.entity.Example;

import javax.print.DocFlavor;

@Service
public class LoginServiceImpl implements LoginService {
private static final Logger logger= LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    MyMapper myMapper;

    @Autowired
    RedisService redisService;
    @Override
    public TbUser login(String username, String password) {

        TbUser tbUser=null;
        String json = redisService.get(username);
        System.out.println("json = " + json);
        json = String.valueOf(json);
        if ("null".equals(json)){
            System.out.println("hello world");
            Example example=new Example(TbUser.class);
            example.createCriteria().andEqualTo("username",username);

            tbUser = (TbUser) myMapper.selectOneByExample(example);
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (tbUser!=null&&tbUser.getPassword().equals(password)){
                try {
                    redisService.put(username,MapperUtils.obj2json(tbUser));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return tbUser;
            } else {
                return null;
            }

        } else {
            try {
                tbUser = MapperUtils.json2pojo(json, TbUser.class);
            } catch (Exception e) {
                logger.warn("触发熔断：{}"+e.getMessage());
            }
        }
        return tbUser;
    }

    public static void main(String[] args) {
        System.out.println("null"==null);
    }
    }

